﻿using DiLe.Mes.Application.Common;
using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Application.Common.Mould;
using DiLe.Mes.Application.Handler;
using DiLe.Mes.Application.Local;
using DiLe.Mes.Local.Controllers.APP.Dto;
using DiLe.Mes.Model.Common.Equipment.Entity.Manage;
using DiLe.Mes.Model.Common.Mould.Entity.Info;
using DiLe.Mes.Model.Common.WorkOrder.Entity;
using MapleLeaf.Core.Serilog;
using Microsoft.AspNetCore.Authorization;

namespace DiLe.Mes.Local.Controllers.APP
{
    /// <summary>
    /// 
    /// </summary>
    [ApiExplorerSettings(GroupName = ApiLocalGroupConst.Other)]
    [AllowAnonymous]
    public class PDAController : ApiBaseController {

        #region 属性
        private readonly WorkOrderClient _workOrder;
        private readonly EquipmentManageClient _equipmentManage;
        private readonly EquipmentExjosnHandler _equipmentHandler;
        private readonly SystemClient _systemClient;
        private readonly MouldInfoClient _mouldInfo;
        private readonly MouldExjosnHandler _mouldExjosnHandler;
        private readonly LocalClient _localClient;
        #endregion



        /// <summary>
        /// 构造函数
        /// </summary>
        public PDAController(WorkOrderClient workOrderClient,
                             EquipmentManageClient equipmentManage,
                             EquipmentExjosnHandler equipmentExjosnHandler,
                             SystemClient systemClient,
                             MouldInfoClient mouldInfoClient,
                             LocalClient localClient,
                             MouldExjosnHandler mouldExjosnHandler) {
            _workOrder = workOrderClient;
            _equipmentManage = equipmentManage;
            _equipmentHandler = equipmentExjosnHandler;
            _systemClient = systemClient;
            _mouldInfo = mouldInfoClient;
            _localClient = localClient;
            _mouldExjosnHandler = mouldExjosnHandler;
        }
        /// <summary>
        /// 获取设备信息
        /// </summary>
        /// <param name="deviceNo">设备编码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetEquipmentInfo(string deviceNo) {
            SerilogLogHelper.WriteSystemLog($"设备{deviceNo} 开始扫码！");
            var info = await _equipmentManage.GetEquipmentInfoAsync(p => p.Code == deviceNo);
            if (info == null) {
                return Fail($"设备编码【{deviceNo}】不存在!");
            }
            //制程
            var process = await _systemClient.GetProcessInfoAsync(info.ProcessId);
            info.ExtJson.Add("ProcessName", process?.Name);
            info.ExtJson.Add("ProcessCode", process?.Code);
            //开工记录
            var startworkrecord = await _workOrder.GetStartWorkRecordInfoAsync(p => p.EquipmentCode == deviceNo);
            info.ExtJson.Add("WorkOrderCode", startworkrecord?.WorkOrderCode);
            info.ExtJson.Add("OrderCode", startworkrecord?.OrderCode);
            info.ExtJson.Add("ProductName", startworkrecord?.ProductName);

            SerilogLogHelper.WriteSystemLog($"设备{deviceNo} 扫码成功！");
            return Success(info);
        }
        /// <summary>
        /// 获取模具信息
        /// </summary>
        /// <param name="mouldCode">模具编码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<MouldInfoEntity>>> GetMouldInfo(string mouldCode) {
            var list = new List<MouldInfoEntity>();
            SerilogLogHelper.WriteSystemLog($"设备{mouldCode} 开始扫码！");
            var info = await _mouldInfo.GetMouldInfoAsync(p => p.Code == mouldCode);
            if (info == null) {
                return Fail(list, $"模具编码【{mouldCode}】不存在!");
            }
            list = await _mouldInfo.GetMouldInfoListAsync(p => p.MouldGroupCode == info.MouldGroupCode);
            await _mouldExjosnHandler.FillMouldInfoExjosn(list);

            SerilogLogHelper.WriteSystemLog($"设备{mouldCode} 扫码成功！");
            return Success(list);
        }
        #region 开工记录
        /// <summary>
        /// 保存开工记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveStartWorkRecord(StartWorkRecordDto dto) {
            dto.Model.MouldNumber = await GetFormingTotalTimes(dto.Model.EquipmentCode);
            dto.Model.StartWorkTime = DateTime.Now;
            var resId = await _workOrder.SaveStartWorkRecordAsync(dto.Model);
            if (!dto.Relations.None()) {
                await _workOrder.InsertStartWorkRecord2MouldInfoAsync(resId, dto.Relations);
            }
            return Success();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetFormingTotalTimeList(string code) {
            var list = await _equipmentManage.GetEquipmentTypeListAsync();
            var info = await _equipmentManage.GetEquipmentInfoModelByCode(code);
            var name = GetParentType(info.EquipmentTypeId, list);
            switch (name) {
                case "成型机":
                    var data = _localClient.GetCurrentTimePointInfo(info.EquipmentSign);
                    return Success(data);
                case "AOI":
                    var dataAOI = _localClient.GetCurrentTimeAOIPointInfo(info.EquipmentSign);
                    return Success(dataAOI);
                case "冲切机":
                    var dataTrim = _localClient.GetCurrentTrimPointInfoList(info.EquipmentSign);
                    return Success(dataTrim);
                default:
                    break;
            }
            return Success("类型不匹配");
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private async Task<int> GetFormingTotalTimes(string code) {
            int totalTimes = 0;
            var list = await _equipmentManage.GetEquipmentTypeListAsync();
            var info = await _equipmentManage.GetEquipmentInfoModelByCode(code);
            var name = GetParentType(info.EquipmentTypeId, list);
            switch (name) {
                case "成型机":
                    var data = _localClient.GetCurrentTimePointInfo(info.EquipmentSign);
                    totalTimes = data?.FormingTotalTimes?.ToInt() ?? 0;
                    break;
                case "AOI":
                    var dataAOI = _localClient.GetCurrentTimeAOIPointInfo(info.EquipmentSign);
                    totalTimes = dataAOI?.CheckTotalTimes?.ToInt() ?? 0;
                    break;
                case "冲切机":
                    var dataTrim = _localClient.GetCurrentTrimPointInfoList(info.EquipmentSign);
                    totalTimes = dataTrim?.TrimingTotalTimes?.ToInt() ?? 0;
                    break;
                default:
                    break;
            }
            return totalTimes;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="typeid"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        private string GetParentType(long typeid, List<EquipmentTypeEntity> list) {
            string? name = "";
            var data = list.FirstOrDefault(p => p.Id == typeid);
            if (data?.ParentId != null && data?.ParentId > 0) {
                name = GetParentType(data.ParentId.Value, list);
            } else {
                name = data?.Name;
            }
            return name ?? "";
        }
        /// <summary>
        /// 获取开工记录列表(默认只查当天的)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetStartWorkRecordList() {
            var res = await _workOrder.GetStartWorkRecordListAsync(p => p.CreateTime >= DateTime.Now.Date);
            await FillStartWorkRecord(res);
            return Success(res);
        }
        /// <summary>
        /// 获取开工记录详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetStartWorkRecord(long id) {
            var res = await _workOrder.GetStartWorkRecordInfoAsync(id);
            await FillStartWorkRecord(new List<StartWorkRecordEntity> { res });
            return Success(res);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataList"></param>
        private async Task FillStartWorkRecord(List<StartWorkRecordEntity> dataList) {
            if (dataList.None()) {
                return;
            }
            var equipmentCodeList = dataList.Select(p => p.EquipmentCode).Distinct();
            var equipmentlist = await _equipmentManage.GetEquipmentInfoListAsync(x => equipmentCodeList.Contains(x.Code));
            foreach (var item in dataList) {
                var equipment = equipmentlist.FirstOrDefault(p => p.Code == item.EquipmentCode);
                item.ExtJson.Add("EquipmentName", equipment?.Name);
            }
        }
        #endregion
        #region 报工记录
        /// <summary>
        /// 保存报工记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveReportWorkRecord(ReportWorkRecordEntity recordEntity) {
            recordEntity.MouldNumber = await GetFormingTotalTimes(recordEntity.EquipmentCode);
            recordEntity.ReportWorkTime = DateTime.Now;
            await _workOrder.SaveReportWorkRecordAsync(recordEntity);
            return Success();
        }
        /// <summary>
        /// 获取报工记录列表(默认只查当天的)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetReportWorkRecordList() {
            var res = await _workOrder.GetReportWorkRecordListAsync(p => p.CreateTime >= DateTime.Now.Date);
            return Success(res);
        }
        /// <summary>
        /// 获取报工记录详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetReportWorkRecord(long id) {
            var res = await _workOrder.GetReportWorkRecordInfoAsync(id);
            return Success(res);
        }
        #endregion
        #region 模具变更
        /// <summary>
        /// 保存模具变更
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveMouldChange(List<MouldChangeEntity> recordEntitys) {
            if (recordEntitys.None()) {
                return Fail("数据异常");
            }
            var number = await GetFormingTotalTimes(recordEntitys.First().EquipmentCode);
            foreach (var recordEntity in recordEntitys) {
                recordEntity.MouldNumber = number;
            }
            var res = await _workOrder.InertMouldChangeListAsync(recordEntitys);
            return res > 0 ? Success() : Fail();
        }
        #endregion
    }
}
